package com.hsd.core.tags.base;

import javax.servlet.jsp.JspException;

import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.tags.HtmlEscapingAwareTag;
import org.springframework.web.util.ExpressionEvaluationUtils;
import org.springframework.web.util.HtmlUtils;

import com.hsd.core.tags.helper.TagWriter;

/**
 * 标签基类
 * @author Abdi
 * @description
 * @created Oct 25, 2013 2:20:46 PM
 */
@SuppressWarnings("serial")
public abstract class AbstractTag extends HtmlEscapingAwareTag {
	/**
	 * 输出标签
	 * @param tagWriter
	 * @return
	 * @throws JspException
	 */
	protected abstract int writeTagContent(TagWriter tagWriter)
			throws JspException;

	
	/**
	 * 调用输出标签方法
	 * @return
	 * @throws Exception
	 */
	@Override
	protected int doStartTagInternal() throws Exception {
		return writeTagContent(createTagWriter());
	}

	@Override
	protected boolean isDefaultHtmlEscape() {
		Boolean defaultHtmlEscape = getRequestContext().getDefaultHtmlEscape();
		return (defaultHtmlEscape == null || defaultHtmlEscape.booleanValue());
	}

	protected TagWriter createTagWriter() {
		return new TagWriter(this.pageContext);
	}
	
	/**
	 * 获取EL表达式的值
	 * @param attributeName
	 * @param value
	 * @return
	 * @throws JspException
	 */
	protected Object evaluate(String attributeName, Object value) throws JspException {
		if (value instanceof String) {
			return ExpressionEvaluationUtils.evaluate(attributeName, (String) value, this.pageContext);
		}
		else {
			return value;
		}
	}
	
	protected boolean evaluateBoolean(String attributeName, String value) throws JspException {
		Object evaluated = ExpressionEvaluationUtils.evaluate(attributeName, value, this.pageContext);
		return (Boolean.TRUE.equals(evaluated) ||
				(evaluated instanceof String && Boolean.valueOf((String) evaluated)));
	}
	
	/**
	 * 输出指定属性
	 * @param tagWriter
	 * @param attributeName
	 * @param value
	 * @throws JspException
	 */
	protected final void writeOptionalAttribute(TagWriter tagWriter,
			String attributeName, String value) throws JspException {

		if (value != null) {
			tagWriter.writeOptionalAttributeValue(attributeName,
					getDisplayString(evaluate(attributeName, value)));
		}
	}
	
	/**
	 * 显示值
	 * @param value
	 * @return
	 */
	protected String getDisplayString(Object value) {
		return getDisplayString(value, isHtmlEscape());
	}
	
	/**
	 * 特殊符号处理
	 * @param value
	 * @param htmlEscape
	 * @return
	 */
	public static String getDisplayString(Object value, boolean htmlEscape) {
		String displayValue = ObjectUtils.getDisplayString(value);
		return (htmlEscape ? HtmlUtils.htmlEscape(displayValue) : displayValue);
	}
}
